#!/usr/bin/env python
from models import *
from tools import *
import os,datetime,time,urllib,tarfile,sys

PRONAME=settings.ProteinName

# Set start time for running on the cluster
# The format of start time is %Y%m%d%H%M%S. See http://docs.python.org/lib/module-time.html
if os.environ.has_key('DVSDMS_STARTTIME'):
    starttime=datetime.datetime.strptime(os.environ['DVSDMS_STARTTIME'],'%Y%m%d%H%M%S')
else:
    starttime=datetime.datetime.now()+datetime.timedelta(weeks=4)

WORKDIRROOT=settings.TMPDIR
if len(sys.argv)>1:
    WORKDIR=sys.argv[1]
else:
    WORKDIR=os.path.join(WORKDIRROOT,PRONAME+'_'+'%f'%time.time())
hardcheck(WORKDIR)
os.chdir(WORKDIR) # change current dir

TEMPLATE='template.tgz'
urllib.urlretrieve(settings.TemplateFile,TEMPLATE)

# extract tar file
tar1=tarfile.open(TEMPLATE)
tar1.extractall()
tar1.close()

LIGNAME=settings.LIGNAME
DLGNAME=LIGNAME+'.dlg'
PDBQT=LIGNAME+'.pdbqt' # need pdb file to make it
PDB=LIGNAME+'.pdb'

while parsecmd(settings.CmdFile):
    # check the starttime
    if datetime.datetime.now()-starttime>datetime.timedelta(hours=(settings.QWallTime-settings.SingRunTime)):
        break
    
    locktable(settings.MoleculeTagTableName)
    moltag1=MOLTAG.query.filter(MOLTAG.status==6).order_by('').first()
    # if there is no molecule left, break the loop.
    if moltag1==None:
        break
    moltag1.update(status=1,
                   tag=os.uname()[1][:11]+datetime.datetime.now().strftime('%m%d%H%M'))
    unlock()
    mol1=moltag1.mol    
    mol1.writePDB(PDB)
    pdb2pdbqt(PDB)
    autodock(PDBQT,DLGNAME)
    moltag1.update(status=2)
    dlg2pdb(DLGNAME,PDBQT,mol1)
    
